﻿using System.Data.Common;
using System;
using System.Threading.Tasks;

namespace DataAccess
{
    /// <summary>
    /// A command that returns a single value when executed
    /// </summary>
    public class ScalarDatabaseCommand<T>
        : DatabaseCommand
    {
        public T ReturnValue { get; set; }

        protected override int Execute(DbCommand command)
        {
            object returnValue = command.ExecuteScalar();

            if (returnValue == null)
            {
                return 0;
            }

            ReturnValue = (T)Convert.ChangeType(returnValue, typeof(T));

            return 1; // Don't know how many rows were modified
        }

        protected override async Task<int> ExecuteAsync(DbCommand command)
        {
            object returnValue = await command.ExecuteScalarAsync();

            if (returnValue == null)
            {
                return 0;
            }

            ReturnValue = (T)Convert.ChangeType(returnValue, typeof(T));

            return 1; // Don't know how many rows were modified
        }
    }
}
